/*
 *  Copyright (C) 2010 takaji
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package examples.helpers;

import dakside.csv.CSVFile;
import dakside.csv.CSVLine;

public class CSVDump {

    /**
     * Dump csv file to console
     * 
     * @param csv
     */
    public static void dumpText(CSVFile csv) {
        for (CSVLine line : csv.getLines()) {
            dumpLineText(line);
        }
    }

    /**
     * Dump csv line to console
     * 
     * @param line
     */
    public static void dumpLineText(CSVLine line) {
        System.out.println(getLineText(line));
    }

    public static String getLineText(CSVLine line) {
        if (line == null) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (Object elem : line.getElements()) {
            builder.append(elem);
            builder.append("\t");
        }
        return builder.toString();
    }

    public static String dumpHTML(CSVFile csv) {
        StringBuilder builder = new StringBuilder();

        builder.append("<table border='1px' width='100%'>").append("\r\n");
        for (CSVLine line : csv.getLines()) {
            builder.append(dumpLineHTML(line));
        }
        builder.append("</table>").append("\r\n");

        return builder.toString();
    }

    public static String dumpLineHTML(CSVLine line) {
        StringBuilder builder = new StringBuilder();
        builder.append("<tr>").append("\r\n");
        for (Object elem : line.getElements()) {
            builder.append("<td>");
            if (elem instanceof String) {
                if (((String) elem).length() == 0) {
                    builder.append("&nbsp;");
                } else {
                    builder.append(dumpHTMLCell((String) elem));
                }
            } else {
                builder.append(elem);
            }
            builder.append("</td>").append("\r\n");
        }
        builder.append("</tr>").append("\r\n");
        return builder.toString();
    }

    public static String dumpHTMLCell(String obj) {
        return obj.replace("\r\n", "<br/>").replace("\n", "<br/>");
    }
}
